//
//  YANetworking.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/2.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa
private let YAErrorDomainName = "com.pyz.error.network"
private enum YANetworkError:Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    private var errorDescrption:String{
        switch self {
        case .emptyDataError:return "空数据"
        case .emptyTokenError:return "Token 为空"
        }
    }
    
    private func error()->NSError{
        return NSError(domain: YAErrorDomainName, code: rawValue, userInfo: [YAErrorDomainName:errorDescrption])
    }
}
//MARK:---定义请求枚举
enum HTTPMethodType:String {
    case GET="GET"
    case POST="POST"
}
//MARK:--- 自定义网络管理者
class YANetworking: AFHTTPSessionManager {
    //MARK:- APP info
    private let appKey = "118858292"
    private let appSecret = "ad354e601c642f25108c5317607676ed"
    let redirect_uri="http://www.baidu.com"
    
    //MARK:---单例
    static let sharedTools:YANetworking = {
        var instance = YANetworking(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    //MARK:---获取授权码的URL
    var URLForGETOAuthCode:NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    //MARK:---获取访问令牌
    func loadAccessTokenWithCode(code:String)->RACSignal{
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri];
        return request(.POST, URLString: urlString, parameters: params, withToken:false)
    }
    //MARK:---加载用户信息
    func loadUserInfoFromToos(uid:String)->RACSignal{
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        
        return request(.GET, URLString: urlString, parameters: params)
    }
     //MARK:--- 发布微博
    func sendStatus(status:String,image:UIImage?)->RACSignal{
        let params = ["status":status]
        if image == nil {
            //update
            return request(.POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: params)
        }else{
            //upload
            return upload("https://upload.api.weibo.com/2/statuses/upload.json", parameters: params,image:image!)
        }
    }
     //MARK:--- 判断token是否有值
    private func appendToken(inout parameters:[String:AnyObject]?)->Bool{
        guard let token = YAUserAcountVM.sharedUserAccount.accessToken else
        {
            return false
        }
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        parameters!["access_token"] = token
        
        return true
    }
     //MARK:--- 加载微博数据
    func loadStatus(since_id since_id:Int,max_id:Int)->RACSignal{
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var params = [String:AnyObject]()
        if since_id>0{
            params["since_id"] = since_id
        }else if max_id > 0 {
            params["max_id"] = max_id
        }
        return request(.GET, URLString: urlString, parameters: params)
    }
    //MARK:--- 封装AFN的网络请求
    ///
    ///  :param: method     请求类型
    ///  :param: URLString  请求资源路径URL
    ///  :param: parameters 请求参数
    //   withToken:  是否包含 accessToken，默认带 token 访问 (加载用户信息时)
    ///
    ///  :returns: 信号资源
    func request(method:HTTPMethodType,URLString:String,var parameters:[String:AnyObject]?,withToken:Bool = true)->RACSignal{
        return RACSignal.createSignal({ (subscribers) -> RACDisposable! in
            //判断token
            if withToken && !self.appendToken(&parameters){
                subscribers.sendError(NSError(domain: "comm.pyz.error", code: -407401, userInfo: ["errorMsg" : "令牌Token为空"]))
                return nil
            }
            let successClosure = {
                (task:NSURLSessionDataTask,result:AnyObject)->Void in
                subscribers.sendNext(result)
                subscribers.sendCompleted()
            }
            let errorClosure = {
                (task:NSURLSessionDataTask,error:NSError)->Void in
                subscribers.sendError(error)
                subscribers.sendCompleted()
            }
            if method == HTTPMethodType.GET {
                self.GET(URLString, parameters: parameters,success:successClosure,failure:errorClosure)
            }
            else
            {
                self.POST(URLString, parameters: parameters,success:successClosure,failure:errorClosure)
            }
            
            return nil
        })
    }
     //MARK:--- 上传文件
    private func upload(URLString:String, var parameters:[String:AnyObject]?,image:UIImage)->RACSignal{
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            if !self.appendToken(&parameters){
                subscriber.sendError(NSError(domain: "comm.pyz.error", code: -407401, userInfo: ["errorMsg" : "令牌Token为空"]))
                return nil
            }
            //调用AFN的上传方法
            self.POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //将图像转换成二进制
                let data = UIImagePNGRepresentation(image)!
                //拼接协议数据
                formData.appendPartWithFileData(data,
                name:"pic",
                fileName:"xxx",
                mimeType:"application/octet-stream")
                }, success: { (_, result) -> Void in
                    subscriber.sendNext(result)
                    subscriber.sendCompleted()
                }, failure: { (_, error) -> Void in
                    printLog(error, logError: true)
                    subscriber.sendError(error)
            })
            return nil
      })
    }
}